#include <stdio.h>
#include <time.h>
#include <pthread.h>

/* For safe condition variable usage, must use a boolean predicate and  */
/* a mutex with the condition.                                          */
int                 workToDo = 0;
pthread_cond_t      cond  = PTHREAD_COND_INITIALIZER;
pthread_mutex_t     mutex = PTHREAD_MUTEX_INITIALIZER;

#define NTHREADS                3
#define WAIT_TIME_SECONDS       5

void *threadfunc(void *parm)
{
  int               rc;
  time_t tt_now;
  timespec   ts;

  rc = pthread_mutex_lock(&mutex);

  /* Usually worker threads will loop on these operations */
  while (1) {
    tt_now = time(NULL);
    /* Convert from timeval to timespec */
	ts.tv_sec  = (long)tt_now + WAIT_TIME_SECONDS;
    ts.tv_nsec = 0;

    while (!workToDo) {
      printf("Thread blocked\n");
      rc = pthread_cond_timedwait(&cond, &mutex, &ts);
      /* If the wait timed out, in this example, the work is complete, and   */
      /* the thread will end.                                                */
      /* In reality, a timeout must be accompanied by some sort of checking  */
      /* to see if the work is REALLY all complete. In the simple example    */
      /* we'll just go belly up when we time out.                            */
      if (rc == ETIMEDOUT) {
        printf("Wait timed out!\n");
        rc = pthread_mutex_unlock(&mutex);
        pthread_exit(NULL);
      }
    }

    printf("Thread consumes work here\n");
    workToDo = 0;
  }

  rc = pthread_mutex_unlock(&mutex);
  return NULL;
}